﻿using AutoMapper;
using B.S.Ingredients.APIRead.Application.Command.Products;
using B.S.Ingredients.APIRead.DTOs;
using B.S.Ingredients.Domain;
using B.S.Ingredients.ErrorCode;
using B.S.Ingredients.Infartructrue.Interfaces;
using MediatR;
using Microsoft.Extensions.Configuration;

namespace B.S.Ingredients.APIRead.Application.CommandHandler.ProductHandler
{
    public class ProdictQueryCommandHandler : IRequestHandler<ProdictQueryCommand, APIResult<APIPageing<List<ProductDTO>>>>
    {
        public ProdictQueryCommandHandler(IBaseRepository<Product> repository,IBaseRepository<ProduciNameClass> productNameRepository,IMapper mapper )
        {
            Repository = repository;
            ProductNameRepository = productNameRepository;
            Mapper = mapper;
        }

        public IBaseRepository<Product> Repository { get; }
        public IBaseRepository<ProduciNameClass> ProductNameRepository { get; }
        public IMapper Mapper { get; }


        public async Task<APIResult<APIPageing<List<ProductDTO>>>> Handle(ProdictQueryCommand request, CancellationToken cancellationToken)
        {
            var path = Repository.GetAll();
            if(request.shopName>0)
            {
                path = path.Where(a => a.ProdId == request.shopName);
            }
            if(request.nums>0)
            {
                path = path.Where(a => a.DayNum == request.nums);
            }
            if(!string.IsNullOrEmpty(request.Boss))
            {
                path = path.Where(a => a.Enterprises.Contains(request.Boss));
            }

            var listDto = Mapper.Map<List<ProductDTO>>(path.ToList());
            foreach(var item in listDto)
            {
                item.ProdName = ProductNameRepository.GetAll().FirstOrDefault(a => a.ProdId == item.ProdId)?.ProdName;
            }

            var totalCount=listDto.Count();
            var pageCount = (int)Math.Ceiling(totalCount * 1.0 / request.PageSize);
            var list=listDto.OrderByDescending(a=>a.CreateTime).Skip((request.PageIndex-1)*request.PageSize).Take(request.PageSize).ToList();
          
            return new APIResult<APIPageing<List<ProductDTO>>>
            {
                Code = ResultCode.success,
                Mag = "",
                Data = new APIPageing<List<ProductDTO>>
                {
                    TotalCount = totalCount,
                    PageCount = pageCount,
                    Data = list
                }
            };

          
        }

    }
}
